home *** CD-ROM | disk | FTP | other *** search
/ PC-X 1997 October / pcx14_9710.iso / swag / delphi.swg / 0222_Re: Find previous instance.pas < prev    next >
Encoding:
Pascal/Delphi Source File  |  1997-03-04  |  1.6 KB  |  59 lines

  1.  
  2. {
  3. Here is some code I found a while back that will work in D1 or D2.  It
  4. checks for previous instance and if the program is already running, it will
  5. activate the previous instance including pulling up an iconic program.  I
  6. have enclosed the source in an imaginary project (.dpr) file.
  7.  
  8. ----- begin code for Check.dpr -----
  9. }
  10. program Check;
  11.  
  12. uses  WinTypes, WinProcs, SysUtils, Forms,
  13.   MainForm in 'MAIN.PAS' {Form1},
  14.   SecondForm in 'SECOND.PAS' {Form2},
  15.   ThirdForm in 'THIRD.PAS' {Form3};
  16.  
  17. {$R *.RES}
  18. {$IFDEF Win32}
  19.   var Mutex: THandle;
  20. {$ENDIF}
  21.  
  22. procedure CheckPrevInst;
  23.   var PrevWnd: HWnd;
  24.   begin
  25.     {$IFDEF Win32}
  26.       Mutex:=CreateMutex(NIL, False, 'SingleInstanceProgramMutex');
  27.       if WaitForSingleObject(Mutex, 10000)=WAIT_TIMEOUT then Halt;
  28.     {$ELSE}
  29.       if HPrevInst=0 then Exit;
  30.     {$ENDIF}
  31.     PrevWnd:=FindWindow('TOneInstanceForm1', '1-Instance Program');
  32.     if PrevWnd<>0 then PrevWnd:=GetWindow(PrevWnd, GW_OWNER);
  33.     if PrevWnd<>0 then begin
  34.       if IsIconic(PrevWnd) then ShowWindow(PrevWnd, SW_SHOWNORMAL)
  35.       else  {$IFDEF Win32}
  36.         SetForegroundWindow(PrevWnd);
  37.       {$ELSE}
  38.         BringWindowToTop(PrevWnd);
  39.       {$ENDIF}
  40.       Halt;
  41.       end;
  42.     end;
  43.  
  44. begin
  45.   try
  46.     CheckPrevInst;
  47.     Application.CreateForm(TOneInstanceForm1, OneInstanceForm1);
  48.   finally
  49.     {$IFDEF Win32}
  50.       OneInstanceForm1.HandleNeeded;
  51.       ReleaseMutex(Mutex);
  52.       CloseHandle(Mutex);
  53.     {$ENDIF}
  54.   end;
  55.   Application.CreateForm(TForm2, Form2);
  56.   Application.CreateForm(TForm3, Form3);
  57.   Application.Run;
  58.   end.
  59.